import pyshark
import requests
from datetime import datetime, timedelta, timezone
headers = {'Host': '192.168.1.100:9200',
           'Content-Type': 'application/json'}

cap = pyshark.FileCapture('cap-6-11.pcap', keep_packets=False)  # 读取pcap文件,数据包被读取后,不在内存中保存!节约内存!

tzutc_0 = timezone(timedelta(hours=0))  # 设置时区为UTC


def write_pkt_mongodb(pkt):
    pkt_dict = {}
    # 使用Pyshark获取数据包中的所有字段
    for layer in pkt.__dict__.get('layers'):
        pkt_dict.update(layer.__dict__.get('_all_fields'))
    pkt_dict_final = {}
    # 把字段分割成为字典
    for key, value in pkt_dict.items():
        # 防止空键
        if key == '' and 'Source GeoIP' in value:
            value.split(':')
            pkt_dict_final[value.split(':')[0].strip()] = value.split(':')[1].strip()
        elif key == '':
            continue
        else:
            # 替换键中的'.'到'_'
            pkt_dict_final[key.replace('.', '_')] = value
    # 格式为:2018-04-23T10:45:13.899Z. Note that we only have milliseconds and the T as separator and Z indicating UTC.
    # E的时间为UTC,所以需要切换时区
    pkt_dict_final.update({"sniff_time": pkt.sniff_time.astimezone(tzutc_0).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3]+'Z'})
    pkt_dict_final.update({'highest_layer': pkt.highest_layer})
    # 把数据导入E
    requests.post('http://192.168.1.100:9200/pyshark/pkts/', headers=headers, json=pkt_dict_final)


# 把函数应用到数据包
cap.apply_on_packets(write_pkt_mongodb)

